package com.rbac.admin.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * Base64转MultipartFile工具类
 */
public class Base64DecodeMultipartFile implements MultipartFile {

    private final byte[] imgContent;
    private final String header;

    public Base64DecodeMultipartFile(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    @Override
    public String getName() {
        return System.currentTimeMillis() + Math.random() + "." + getExtension();
    }

    @Override
    public String getOriginalFilename() {
        return System.currentTimeMillis() + "." + getExtension();
    }

    @Override
    public String getContentType() {
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        try (FileOutputStream fos = new FileOutputStream(dest)) {
            fos.write(imgContent);
        }
    }

    /**
     * 获取文件扩展名
     */
    private String getExtension() {
        return header.contains("image/jpeg") ? "jpg" :
                header.contains("image/png") ? "png" :
                header.contains("image/gif") ? "gif" :
                header.contains("image/bmp") ? "bmp" : "jpg";
    }

    /**
     * Base64转MultipartFile
     *
     * @param base64 Base64字符串
     * @return MultipartFile
     */
    public static MultipartFile base64Convert(String base64) {
        String[] baseStrs = base64.split(",");
        
        // 如果不是正常的Base64图片字符串，返回null
        if (baseStrs.length < 2) {
            return null;
        }
        
        byte[] b = Base64.getDecoder().decode(baseStrs[1]);
        
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }
        
        return new Base64DecodeMultipartFile(b, baseStrs[0]);
    }
} 